package com.cross.xml;

import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.cross.core.AbstractReader;
import com.cross.core.Column;
import com.cross.core.Header;
import com.cross.core.Item;
import com.cross.core.Row;

public class SimpleXmlReader extends AbstractReader {

	private SAXReader reader = new SAXReader();
	private Document document = null;
	Element root = null;
	Iterator<Element> iterator = null;

	public SimpleXmlReader(File file) throws DocumentException {
		document = reader.read(file);
		root = document.getRootElement(); // Get the root node of XML
		iterator = root.elementIterator();
		header = new Header();
	}
	
	public SimpleXmlReader(InputStream is) throws DocumentException {
		document = reader.read(is);
		root = document.getRootElement(); // Get the root node of XML
		iterator = root.elementIterator();
		header = new Header();
	}
	
	public SimpleXmlReader(Reader r) throws DocumentException {
		document = reader.read(r);
		root = document.getRootElement(); // Get the root node of XML
		iterator = root.elementIterator();
		header = new Header();
	}

	@Override
	protected boolean nextRow() {
		return nextRowImpl();
	}

	private boolean nextRowImpl() {
		if(!iterator.hasNext()){
			return false;
		}
		currentRow = toRow(iterator.next());
		return null != currentRow;
	}

	private Row toRow(Element e) {
		Row row = new Row();
		Header header = new Header();
		header.setObjectName(e.attributeValue("objectName").trim());
		Iterator<Element> iterator = e.elementIterator();
		Element child = null;
		int i=0;
		while (iterator.hasNext()) {
			child = iterator.next();
			row.append(toItem(child));
			header.add(new Column(i++, child.getName(), child.attributeValue("type").trim()));
		}
		super.header.refresh(header);
		return row;
	}

	private Item toItem(Element e) {
		Item item = new Item(e.getData(), e.attributeValue("type").trim());
		return item;
	}

	@Override
	public void close() {

	}
}
